<template>
  <div class="dashboard">
    <h3>欢迎使用后台管理系统</h3>
    <div class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="system-card">
            <template #header>
              <div class="card-header">
                <span>系统信息</span>
                <el-button type="primary" link @click="refreshSystemInfo">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </template>
            <div class="info-item">
              <span class="label">操作系统：</span>
              <span>{{ systemInfo.platform }} {{ systemInfo.arch }}</span>
            </div>
            <div class="info-item">
              <span class="label">系统版本：</span>
              <span>{{ systemInfo.release }}</span>
            </div>
            <div class="info-item">
              <span class="label">主机名：</span>
              <span>{{ systemInfo.hostname }}</span>
            </div>
            <div class="info-item">
              <span class="label">CPU型号：</span>
              <span>{{ systemInfo.cpus?.model }}</span>
            </div>
            <div class="info-item">
              <span class="label">CPU核心数：</span>
              <span>{{ systemInfo.cpus?.cores }} 核</span>
            </div>
            <div class="info-item">
              <span class="label">系统运行：</span>
              <span>{{ systemInfo.uptime }}</span>
            </div>
            <div class="info-item">
              <span class="label">当前用户：</span>
              <span>{{ systemInfo.userInfo?.username }}</span>
            </div>
            <div class="info-item">
              <span class="label">IP地址：</span>
              <span>{{ systemInfo.network?.address || '未连接' }}</span>
            </div>
            <div class="info-item">
              <span class="label">MAC地址：</span>
              <span>{{ systemInfo.network?.mac || '未知' }}</span>
            </div>
          </el-card>

          <el-card class="system-card" style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>磁盘信息</span>
              </div>
            </template>
            <template v-if="systemInfo.drives?.length">
              <div v-for="drive in systemInfo.drives" :key="drive.name" class="drive-info">
                <div class="drive-header">
                  <span class="drive-name">{{ drive.name }}</span>
                  <span class="drive-usage">{{ drive.used }} / {{ drive.total }}</span>
                </div>
                <el-progress 
                  :percentage="Number(drive.usagePercent)"
                  :status="getDriveStatus(drive.usagePercent)"
                />
              </div>
            </template>
            <el-empty v-else description="无法获取磁盘信息" />
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="system-card">
            <template #header>
              <div class="card-header">
                <span>系统负载</span>
                <el-tag type="success" v-if="isLowLoad" size="small">负载正常</el-tag>
                <el-tag type="warning" v-else-if="isMediumLoad" size="small">负载较高</el-tag>
                <el-tag type="danger" v-else size="small">负载过高</el-tag>
              </div>
            </template>
            <div class="info-item">
              <span class="label">内存使用：</span>
              <el-progress 
                :percentage="Number(systemLoad.memory?.usagePercent)" 
                :status="getMemoryStatus()"
              />
            </div>
            <div class="info-item">
              <span class="label">内存详情：</span>
              <span>已用 {{ systemLoad.memory?.used }} / 总共 {{ systemLoad.memory?.total }}</span>
            </div>
            <div class="info-item">
              <span class="label">CPU使用率：</span>
              <div class="cpu-usage">
                <template v-for="(usage, index) in systemLoad.cpuUsage" :key="index">
                  <div class="cpu-core">
                    <span class="core-label">核心{{ index + 1 }}:</span>
                    <el-progress 
                      :percentage="Number(usage)"
                      :status="getCpuStatus(usage)"
                      :stroke-width="10"
                    />
                  </div>
                </template>
              </div>
            </div>
            <div class="info-item">
              <span class="label">系统负载：</span>
              <span>{{ formatLoadAvg(systemLoad.loadavg) }}</span>
            </div>
          </el-card>

          <el-card class="system-card" style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>进程信息</span>
              </div>
            </template>
            <div class="info-item">
              <span class="label">进程ID：</span>
              <span>{{ systemLoad.processInfo?.pid }}</span>
            </div>
            <div class="info-item">
              <span class="label">父进程ID：</span>
              <span>{{ systemLoad.processInfo?.ppid }}</span>
            </div>
            <div class="info-item">
              <span class="label">Node版本：</span>
              <span>{{ systemLoad.processInfo?.nodeVersion }}</span>
            </div>
            <div class="info-item">
              <span class="label">进程内存：</span>
              <span>{{ formatBytes(systemLoad.processInfo?.memoryUsage?.heapUsed) }} / {{ formatBytes(systemLoad.processInfo?.memoryUsage?.heapTotal) }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-card class="welcome-card" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <div class="info-item">
          <span class="label">当前时间：</span>
          <span>{{ currentTime }}</span>
        </div>
        <div class="info-item">
          <span class="label">登录状态：</span>
          <el-tag type="success">已登录</el-tag>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { Refresh } from '@element-plus/icons-vue'

const currentTime = ref(new Date().toLocaleString())
const systemInfo = ref({})
const systemLoad = ref({})
let timer
let loadTimer

const isLowLoad = computed(() => {
  const avgLoad = systemLoad.value.loadavg?.[0] || 0
  return avgLoad < 0.7
})

const isMediumLoad = computed(() => {
  const avgLoad = systemLoad.value.loadavg?.[0] || 0
  return avgLoad >= 0.7 && avgLoad < 0.9
})

const getMemoryStatus = () => {
  const usage = Number(systemLoad.value.memory?.usagePercent || 0)
  if (usage > 90) return 'exception'
  if (usage > 70) return 'warning'
  return 'success'
}

const getCpuStatus = (usage) => {
  const value = Number(usage)
  if (value > 90) return 'exception'
  if (value > 70) return 'warning'
  return 'success'
}

const getDriveStatus = (usagePercent) => {
  const usage = Number(usagePercent)
  if (usage > 90) return 'exception'
  if (usage > 70) return 'warning'
  return 'success'
}

const formatLoadAvg = (loadavg) => {
  if (!loadavg) return '获取中...'
  return `1分钟: ${loadavg[0].toFixed(2)}, 5分钟: ${loadavg[1].toFixed(2)}, 15分钟: ${loadavg[2].toFixed(2)}`
}

const formatBytes = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const refreshSystemInfo = async () => {
  try {
    systemInfo.value = await window.electron.getSystemInfo()
  } catch (error) {
    console.error('获取系统信息失败:', error)
  }
}

const updateSystemLoad = async () => {
  try {
    systemLoad.value = await window.electron.getSystemLoad()
  } catch (error) {
    console.error('获取系统负载失败:', error)
  }
}

onMounted(async () => {
  // 更新时间
  timer = setInterval(() => {
    currentTime.value = new Date().toLocaleString()
  }, 1000)

  // 获取系统信息
  await refreshSystemInfo()

  // 定期更新系统负载
  await updateSystemLoad()
  loadTimer = setInterval(updateSystemLoad, 2000)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  if (loadTimer) {
    clearInterval(loadTimer)
  }
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.dashboard-content {
  margin-top: 20px;
}

.system-card {
  margin-bottom: 20px;
  height: 100%;
}

.welcome-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item {
  margin-bottom: 15px;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
  display: inline-block;
  width: 100px;
}

.cpu-usage {
  flex: 1;
}

.cpu-core {
  margin-bottom: 8px;
}

.core-label {
  display: inline-block;
  width: 60px;
  font-size: 12px;
  color: #909399;
}

.drive-info {
  margin-bottom: 15px;
}

.drive-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.drive-name {
  font-weight: bold;
  color: #606266;
}

.drive-usage {
  color: #909399;
  font-size: 12px;
}

:deep(.el-progress) {
  margin-top: 5px;
  width: calc(100% - 70px);
  display: inline-block;
}

:deep(.el-progress--line) {
  margin-bottom: 0;
}

:deep(.el-card__body) {
  padding: 15px;
}
</style> 